//
var app = getApp();

Page({
    data: {
        siteInfo: app.siteInfo,
        showLoading: 1,
        isLike: true, //初始化收藏
        indicatorDots: true, //是否显示面板指示点
        autoplay: false, //是否自动切换
        interval: 3000, //自动切换时间间隔,3s
        duration: 800, //  滑动动画时长1s
        toView: 'eeede',  //  锚点
        isSelectSpecItemsAll: false,
        selectSpecItems: {},
        selectGoodsItems: {},
        //优惠活动
        activity: [
            {
                activitymoney: 3,    //  优惠金额
                activityfont: '满59元减',   //  优惠文字
                isaid: 0,
                isactivity: true,//初始化优惠活动
            },
            {
                activitymoney: 5,
                activityfont: '满79元减',
                isaid: 1,
                isactivity: true,//初始化优惠活动
            },
            {
                activitymoney: 10,
                activityfont: '满109元减',
                isaid: 2,
                isactivity: true,//初始化优惠活动
            }
        ],

        mainImg: '',//主图
        goodPrice: 99.99,//商品价格
        flowerImgSelect: '',//选中的花色图片
        flowerNameSelect: " ",// 商品参数默认显示
        flowerSelect: 0,//判断是否选中
        isHidden: 0,
        animationData: {},//选择动画
        showModalStatus: false,//显示遮罩
        goodNum: 1,//商品数量
        select: 0,//商品详情、参数切换
    },
    onLoad: function (e) {
        var that = this;
        app.initPage({'navigationBarTitleText': '正在加载'});
        var good_id = that.options.id;
        that.setData({
            'goods_id': good_id,
        });

        app.util.request({
            'url': 'goods/detail',
            'data': {id: good_id},
            'showLoading': true,
            success: function (res) {
                var data = res.data.data;
                //如果是跳转到其他APP
                var link = data.link;
                if (link && link.type == 2) {
                    //跳转到小程序
                    wx.navigateToMiniProgram({
                        appId: link.appid,
                        path: link.url,
                        extraData: link.extra_data,
                        envVersion: link.env_version,
                        success(res) {
                            // 打开成功
                        },
                        fail(res) {

                        }
                    })
                    return;
                }
                var specTitles = [];
                var flowerNameSelect = '';
                var j = 0;
                for (var i in data.spec) {
                    if (j != 0) {
                        flowerNameSelect += ',';
                    }
                    flowerNameSelect += data.spec[i]['title'];
                    j++;
                }
                that.setData({
                    'showLoading': 0,
                    'data': data,
                    'flowerNameSelect': flowerNameSelect,
                    'goodSelectPic': data.thumb,

                });
                //设置商品规格参数，供切换使用
                that.setData({
                    goodSelectPic: data.thumb,
                    goodSelectMarketprice: data.marketprice,
                    goodSelectOptionTitle: '',
                    hasoption: data.hasoption,
                });

                if (data.hasoption == 1) {
                    var spec = data.spec;
                    var option = data.option;
                    that.setData({
                        goodSelectSpec: spec,
                        goodSelectOption: option,
                    });
                } else {
                    var spec = {};
                    var option = {};
                    var isSelectSpecItemsAll = true;
                    that.setData({
                        goodSelectSpec: spec,
                        goodSelectOption: option,
                        isSelectSpecItemsAll: isSelectSpecItemsAll,
                        flowerNameSelect: '',
                    });
                }

                app.initPage({'navigationBarTitleText': data.goodsname});
            }
        })
    },
    addCount() {
        let num = this.data.num;
        num++;
        this.setData({
            num: num
        })
    },

    bindTap(e) {
        const index = parseInt(e.currentTarget.dataset.index);
        this.setData({
            curIndex: index
        })
    },
    //预览图片
    previewImage: function (e) {
        var current = e.target.dataset.src;
        wx.previewImage({
            current: current, // 当前显示图片的http链接
            urls: this.data.imgUrls // 需要预览的图片http链接列表
        })
    },
    //添加收藏
    addCollect() {
        var that = this;
        var params = {};
        params.goods_id = that.data.goods_id;
        params.shop_id = that.data.data.shop_info.id;
        app.util.getUserInfo(() => {
            app.util.request({
                'url': 'goods/collectGoods',
                'data': params,
                'showLoading': false,
                success: function (res) {
                    var data = res.data.data;
                    that.setData({
                        ["data.is_collect"]: data
                    });
                }
            });
        });
    },

    // 领取优惠券
    addActivity: function (e) {
        let index = e.currentTarget.dataset.productid;
        let up = "activity[" + index + "].isactivity"
        this.setData({
            [up]: false
        });
    },

    // 锚点跳转
    jumpTo: function (e) {
        // 获取标签元素上自定义的 data-opt 属性的值
        let target = e.currentTarget.dataset.opt;
        let ato = this.data.toView;
        this.setData({
            toView: target
        });
        console.log(ato);

    },

    /**
     * 添加到购物车
     */
    addToCart: function (e) {
        var that = this;
        var goodNum = this.data.goodNum;
        var goodSelectId = this.data.data.id;

        var isSelectSpecItemsAll = this.data.isSelectSpecItemsAll;
        var flowerNameSelect = this.data.flowerNameSelect;
        if (!isSelectSpecItemsAll) {
            wx.showToast({
                title: '请选择: ' + flowerNameSelect,
                icon: 'none'
            });
            return;
        }

        var selectGoodsItems = this.data.selectGoodsItems || {};
        var selectGoodsItemsArr = Object.keys(selectGoodsItems).map(function (key) {
            return selectGoodsItems[key];
        });

        selectGoodsItemsArr.sort();
        var selectGoodsItemsStr = selectGoodsItemsArr.join(',');

        var param = {};
        param.goods_num = goodNum;
        param.goods_id = goodSelectId;
        param.goods_items = selectGoodsItemsStr;

        app.util.getUserInfo(() => {
            app.util.request({
                'url': 'user/addShopCart', //调用wxapp.php中的doPagePay方法获取支付参数
                data: param,
                showLoading: false,
                'cachetime': '0',
                success(res) {
                    that.setData({
                        'addShopCartLoading': 0,
                    });
                    if (res.data.code == 1) {
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                        });
                        that.hideModal();
                    } else {
                        wx.showModal({
                            title: '系统提示',
                            content: res.data.msg,
                            showCancel: false,
                            success: function (res) {
                                // if (res.confirm) {
                                //     // backApp();
                                // }
                            }
                        })
                    }
                },
                fail(res) {
                }
            })
        });
    },

    /**
     * 立即购买
     */
    saveOrder: function (e) {
        var that = this;
        var goodNum = this.data.goodNum;
        var goodSelectId = this.data.data.id

        var isSelectSpecItemsAll = this.data.isSelectSpecItemsAll;
        var flowerNameSelect = this.data.flowerNameSelect;
        if (!isSelectSpecItemsAll) {
            wx.showToast({
                title: '请选择: ' + flowerNameSelect,
                icon: 'none'
            });
            return;
        }

        var selectGoodsItems = this.data.selectGoodsItems || {};
        var selectGoodsItemsArr = Object.keys(selectGoodsItems).map(function (key) {
            return selectGoodsItems[key];
        });

        selectGoodsItemsArr.sort();
        var selectGoodsItemsStr = selectGoodsItemsArr.join(',');

        var param = {};
        param.is_new = 1;
        param.goods_num = goodNum;
        param.goods_id = goodSelectId;
        param.goods_items = selectGoodsItemsStr;

        app.util.getUserInfo(() => {
            app.util.request({
                'url': 'user/addShopCart', //调用wxapp.php中的doPagePay方法获取支付参数
                data: param,
                showLoading: false,
                'cachetime': '0',
                success(res) {
                    if (res.data.code == 1) {
                        var cartIds = [];
                        cartIds.push(res.data.data);
                        wx.removeStorageSync('toOrderCardIds');
                        wx.setStorageSync('toOrderCardIds', cartIds);//设置去购物车结算的商品id
                        wx.redirectTo({
                            url: '/wxz_superstore/pages/order/confirm',
                        });
                    } else {
                        wx.showModal({
                            title: '系统提示',
                            content: res.data.msg,
                            showCancel: false,
                            success: function (res) {
                                // if (res.confirm) {
                                //     // backApp();
                                // }
                            }
                        })
                    }
                },
                fail(res) {
                }
            })
        });
    },
    //选择商品规格
    selectGoodsItemTap: function (e) {
        var item_id = e.currentTarget.dataset.item_id;
        var item_thumb = e.currentTarget.dataset.item_thumb;
        var spec_id = e.currentTarget.dataset.spec_id;
        var selectSpecItems = this.data.selectSpecItems;//已经选择的spec item
        var selectGoodsItems = this.data.selectGoodsItems;//已经选择的goods item

        var curItem = '';

        if (selectSpecItems) {
            if (selectSpecItems && selectSpecItems[spec_id]) {
                curItem = selectSpecItems[spec_id];
                delete selectGoodsItems[curItem];
                delete selectSpecItems[spec_id];
            }
        }

        if (curItem != item_id) {
            selectSpecItems[spec_id] = item_id;
            selectGoodsItems[item_id] = item_id;
        }

        this.setData({
            selectSpecItems: selectSpecItems,
            selectGoodsItems: selectGoodsItems,
        });

        //规格属性
        if (item_thumb) {
            this.setData({
                goodSelectPic: item_thumb,
            });
        }

        //是否是全选
        var isSelectSpecItemsAll = app.util.objectLength(selectGoodsItems) == app.util.objectLength(this.data.goodSelectSpec);
        this.setData({
            isSelectSpecItemsAll: isSelectSpecItemsAll,
        });

        //排序获取option key
        var selectSpecItemsArr = Object.keys(selectSpecItems).map(function (key) {
            return selectSpecItems[key];
        });
        selectSpecItemsArr.sort();
        var optionKey = selectSpecItemsArr.join(',');

        var optionPrice = 0;
        var optionTitle = '';

        //获取option值
        for (var key in this.data.goodSelectOption) {
            if (this.data.goodSelectOption[key].spec_item_ids == optionKey) {
                optionPrice = this.data.goodSelectOption[key].marketprice;
                optionTitle = this.data.goodSelectOption[key].title;
            }
        }
        if (isSelectSpecItemsAll) {
            this.setData({
                goodSelectMarketprice: app.util.formatCurrency(optionPrice / 100),
                goodSelectOptionTitle: optionTitle,
            });
        }

        var j = 0;
        var k = 0;
        var notselectItemName = '';
        var selectItemName = '';//已经选择的商品规格
        var dataSpec = this.data.data.spec;
        for (var i in dataSpec) {
            if (selectSpecItems[i]) {
                if (j != 0) {
                    selectItemName += ',';
                }
                selectItemName += dataSpec[i]['items'][selectSpecItems[i]]['title'];
                j++;
            } else {
                if (k != 0) {
                    notselectItemName += ',';
                }
                notselectItemName += dataSpec[i]['title'];
                k++
            }
        }
        if (isSelectSpecItemsAll) {
            var flowerNameSelect = selectItemName;
        } else {
            var flowerNameSelect = notselectItemName;
        }
        this.setData({
            flowerNameSelect: flowerNameSelect,
        });
    },

    /**点击运输相关显示页面 */
    viewYun: function () {
        var isH = 2;
        this.onShowWin(isH);
    },

    /**点击显示页面 */
    viewshaoping: function () {
        var isH = 3;
        this.onShowWin(isH);
    },

    /**点击关闭相关显示页面 */
    hideModal: function () {
        this.onholdWin();
    },

    /**弹出页面 */
    onShowWin(isH) {
        var isH = isH;
        var that = this;
        var animation = wx.createAnimation({//动画
            duration: 500,//动画持续时间
            timingFunction: 'linear',//动画的效果 动画从头到尾的速度是相同的
        })
        animation.translateY(0).step()//在Y轴偏移tx，单位px

        this.animation = animation
        that.setData({
            showModalStatus: true,//显示遮罩
            animationData: animation.export()
        })
        that.setData({//把选中值，放入判断值中
            isHidden: isH,
        })
    },
    //弹出商品窗口
    onShowInfo: function (e) {
        this.onShowWin(1);
    },

    /**关闭弹出页面 */
    onholdWin() {
        var that = this;
        that.setData({//把选中值，放入判断值中
            showModalStatus: false,//显示遮罩
            isHidden: 0,
        })
    },
    goodAdd: function (data) {
        var that = this;
        var goodCount = that.data.goodNum + 1;
        that.setData({//商品数量+1
            goodNum: goodCount
        })

    },
    goodReduce: function (data) {

        var that = this;
        var goodCount = that.data.goodNum - 1;
        that.setData({//商品数量+1
            goodNum: goodCount
        })
    },

    /**商品详情、参数切换 */
    changeArea: function (data) {
        var that = this;
        var area = data.currentTarget.dataset.area;
        that.setData({"select": area});

    },

    onShow: function () {
        // this.setData({
        //     includeGroup: this.data.commodityAttr
        // });
        // this.distachAttrValue(this.data.commodityAttr);
        // // 只有一个属性组合的时候默认选中
        // //console.log(this.data.attrValueList);
        // if (this.data.commodityAttr.length == 1) {
        //     for (var i = 0; i < this.data.commodityAttr[0].attrValueList.length; i++) {
        //         this.data.attrValueList[i].selectedValue = this.data.commodityAttr[0].attrValueList[i].attrValue;
        //     }
        //     this.setData({
        //         attrValueList: this.data.attrValueList
        //     });
        // }
    },

    /* 获取数据 */
    distachAttrValue: function (commodityAttr) {
        /**
         将后台返回的数据组合成类似
         {
         attrKey:'型号',
         attrValueList:['1','2','3']
         }
         */
            // 把数据对象的数据（视图使用），写到局部内
        var attrValueList = this.data.attrValueList;
        // 遍历获取的数据
        for (var i = 0; i < commodityAttr.length; i++) {
            for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
                var attrIndex = this.getAttrIndex(commodityAttr[i].attrValueList[j].attrKey, attrValueList);
                // console.log('属性索引', attrIndex);
                // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置
                if (attrIndex >= 0) {
                    // 如果属性值数组中没有该值，push新值；否则不处理
                    if (!this.isValueExist(commodityAttr[i].attrValueList[j].attrValue, attrValueList[attrIndex].attrValues)) {
                        attrValueList[attrIndex].attrValues.push(commodityAttr[i].attrValueList[j].attrValue);
                    }
                } else {
                    attrValueList.push({
                        attrKey: commodityAttr[i].attrValueList[j].attrKey,
                        attrValues: [commodityAttr[i].attrValueList[j].attrValue]
                    });
                }
            }
        }
        // console.log('result', attrValueList)
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                if (attrValueList[i].attrValueStatus) {
                    attrValueList[i].attrValueStatus[j] = true;
                } else {
                    attrValueList[i].attrValueStatus = [];
                    attrValueList[i].attrValueStatus[j] = true;
                }
            }
        }
        this.setData({
            attrValueList: attrValueList
        });
    },
    getAttrIndex: function (attrName, attrValueList) {
        // 判断数组中的attrKey是否有该属性值
        for (var i = 0; i < attrValueList.length; i++) {
            if (attrName == attrValueList[i].attrKey) {
                break;
            }
        }
        return i < attrValueList.length ? i : -1;
    },
    isValueExist: function (value, valueArr) {
        // 判断是否已有属性值
        for (var i = 0; i < valueArr.length; i++) {
            if (valueArr[i] == value) {
                break;
            }
        }
        return i < valueArr.length;
    },
    /* 选择属性值事件 */
    selectAttrValue: function (e) {
        /*
        点选属性值，联动判断其他属性值是否可选
        {
        attrKey:'型号',
        attrValueList:['1','2','3'],
        selectedValue:'1',
        attrValueStatus:[true,true,true]
        }
        console.log(e.currentTarget.dataset);
        */
        var attrValueList = this.data.attrValueList;
        var index = e.currentTarget.dataset.index;//属性索引
        var key = e.currentTarget.dataset.key;
        var value = e.currentTarget.dataset.value;
        if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
            if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
                // 取消选中
                this.disSelectValue(attrValueList, index, key, value);
            } else {
                // 选中
                this.selectValue(attrValueList, index, key, value);
            }
        }
    },
    /* 选中 */
    selectValue: function (attrValueList, index, key, value, unselectStatus) {
        // console.log('firstIndex', this.data.firstIndex);
        var includeGroup = [];
        if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选
            var commodityAttr = this.data.commodityAttr;
            // 其他选中的属性值全都置空
            // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus);
            for (var i = 0; i < attrValueList.length; i++) {
                for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                    attrValueList[i].selectedValue = '';
                }
            }
        } else {
            var commodityAttr = this.data.includeGroup;
        }

        //console.log('选中', commodityAttr, index, key, value);
        for (var i = 0; i < commodityAttr.length; i++) {
            for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
                if (commodityAttr[i].attrValueList[j].attrKey == key && commodityAttr[i].attrValueList[j].attrValue == value) {
                    includeGroup.push(commodityAttr[i]);
                }
            }
        }
        attrValueList[index].selectedValue = value;

        // 判断属性是否可选
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                attrValueList[i].attrValueStatus[j] = false;
            }
        }
        for (var k = 0; k < attrValueList.length; k++) {
            for (var i = 0; i < includeGroup.length; i++) {
                for (var j = 0; j < includeGroup[i].attrValueList.length; j++) {
                    if (attrValueList[k].attrKey == includeGroup[i].attrValueList[j].attrKey) {
                        for (var m = 0; m < attrValueList[k].attrValues.length; m++) {
                            if (attrValueList[k].attrValues[m] == includeGroup[i].attrValueList[j].attrValue) {
                                attrValueList[k].attrValueStatus[m] = true;
                            }
                        }
                    }
                }
            }
        }
        //console.log('结果', includeGroup);

        this.setData({
            attrValueList: attrValueList,
            includeGroup: includeGroup,
        });

        this.showValue(includeGroup, attrValueList);

        var count = 0;
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                if (attrValueList[i].selectedValue) {
                    count++;
                    break;
                }
            }
        }
        if (count < 2) {// 第一次选中，同属性的值都可选
            this.setData({
                firstIndex: index
            });
        } else {
            this.setData({
                firstIndex: -1
            });
        }
    },
    /* 取消选中 */
    disSelectValue: function (attrValueList, index, key, value) {
        var commodityAttr = this.data.commodityAttr;
        attrValueList[index].selectedValue = '';
        // 判断属性是否可选
        for (var i = 0; i < attrValueList.length; i++) {
            for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
                attrValueList[i].attrValueStatus[j] = true;
            }
        }
        this.setData({
            attrValueList: attrValueList
        });

        this.showValue(commodityAttr, attrValueList);

        for (var i = 0; i < attrValueList.length; i++) {
            if (attrValueList[i].selectedValue) {
                this.selectValue(attrValueList, i, attrValueList[i].attrKey, attrValueList[i].selectedValue, true);
            }
        }
    },

    showValue(includeGroup, attrValueList) {
        var shColor = attrValueList[0].attrKey;
        var shValue = attrValueList[0].selectedValue;
        var shSize = attrValueList[1].attrKey;
        var shSizeValue = attrValueList[1].selectedValue;
        if (shValue && shSizeValue) {
            this.setData({
                flowerNameSelect: "已选择：" + shColor + shValue + ' , ' + shSize + shSizeValue
            });
        } else if (!shValue && shSizeValue) {
            this.setData({
                flowerNameSelect: "请选择：" + "颜色"
            });
        } else if (shValue && !shSizeValue) {
            this.setData({
                flowerNameSelect: "请选择：" + "尺码"
            });
        } else {
            this.setData({
                flowerNameSelect: "请选择：" + "尺码颜色"
            });
        }
        this.setData({
            goodPrice: includeGroup[0].price,
            flowerImgSelect: includeGroup[0].flower_image
        });

    },

    submit: function () {
        var value = [];
        for (var i = 0; i < this.data.attrValueList.length; i++) {
            if (!this.data.attrValueList[i].selectedValue) {
                break;
            }
            value.push(this.data.attrValueList[i].selectedValue);
        }
        if (i < this.data.attrValueList.length) {
            wx.showToast({
                title: '请选择完整！',
                icon: 'loading',
                duration: 1000
            })
        } else {
            var valueStr = "";
            for (var i = 0; i < value.length; i++) {
                console.log(value[i]);
                valueStr += value[i] + ",";
            }
            wx.showModal({
                title: '提示',
                content: valueStr,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定')
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
            console.log(valueStr);
        }
    },
})